package com.arpa.ntocc.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.dto.ResourceDTO;
import com.arpa.ntocc.common.domain.entity.Resource;
import com.arpa.ntocc.common.domain.entity.RoleResource;
import com.arpa.ntocc.common.domain.vo.ResourceVO;
import com.arpa.ntocc.common.domain.vo.TreeData;
import com.arpa.ntocc.common.mapper.ResourceMapper;
import com.arpa.ntocc.common.service.IResourceService;
import com.arpa.ntocc.common.service.IRoleResourceService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源 服务实现类
 * </p>
 *
 * @author LEO
 * @since 2019-08-02
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements IResourceService {

    @CreateCache(name = "resources_")
    private Cache<String, Object> resourcesCache;
    @Autowired
    private IRoleResourceService roleResourcesService;

    /**
     * 保存
     * @param entity
     * @return
     */
    @Override
    public boolean save(Resource entity) {
        if(StringUtils.isBlank(entity.getCode())){
            entity.setCode(IdUtil.simpleUUID());
        }
        if(StringUtils.isBlank(entity.getCreatedBy())){
            entity.setCreatedBy(UserUtil.getCode());
        }
        if(StringUtils.isBlank(entity.getBranchCode())){
            entity.setBranchCode(UserUtil.getBranchCode());
        }
        return super.save(entity);
    }

    /**
     * 根据code更新实体
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor={Exception.class})
    public int updateByCode(Resource entity) {
        if(StringUtils.isBlank(entity.getModifiedBy())){
            entity.setModifiedBy(UserUtil.getCode());
        }
        return baseMapper.update(entity,new QueryWrapper<Resource>().lambda().eq(Resource::getCode,entity.getCode()));
    }
    /**
     * 通过层级查询资源列表
     *
     * @param level
     * @return
     */
    @Override
    public List<Resource> selectResourcesByLevel(int level) {
        return baseMapper.selectList(new QueryWrapper<Resource>().lambda().eq(Resource::getLevel, level).orderByAsc(Resource::getSort));
    }

    /**
     * 添加/修改 资源信息
     * TableId 注解存在更新记录，否插入一条记录
     * @param entity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveOrUpdate(ResourceDTO entity) {
        resourcesCache.remove("tree_data");
        Resource resource = new Resource();
        BeanUtil.copyProperties(entity, resource);
        return saveOrUpdate(resource);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    public boolean deleteByIds(List<String> ids) {
        resourcesCache.remove("tree_data");
        return this.removeByIds(ids);
    }

    /**
     * 树结构数据
     * @return 树结构数据
     */
    @Override
    public List<ResourceVO> treeData(String branchCode) {
        List<Resource> resourceList;
        List<ResourceVO> resourceVOList=null;
        if(StringUtils.isNotEmpty(branchCode)){
            resourceList = baseMapper.selectList(new QueryWrapper<Resource>().lambda().eq(Resource::getBranchCode,branchCode));
        }else{
            resourceList = baseMapper.selectList(new QueryWrapper<Resource>());
        }
        if(!CollectionUtils.isEmpty(resourceList)){
            List<ResourceVO> allResourceVOList=resourceList.stream().map(resource -> {
                ResourceVO resourceVO = new ResourceVO();
                BeanUtil.copyProperties(resource,resourceVO);
                return resourceVO ;
            }).collect(Collectors.toList());
            resourceVOList = treeResource(allResourceVOList,0,100);
        }
        return resourceVOList;
    }

    /**
     * 通过角色ID设置资源树选中状态
     * @param data
     * @param roleCode
     */
    @Override
    public void setCheck(List<TreeData> data,String roleCode) {
        List<Object> resourcesId = roleResourcesService.listObjs(new QueryWrapper<RoleResource>().select("resources_id").lambda().eq(RoleResource::getRoleCode, roleCode));
        if(CollUtil.isNotEmpty(resourcesId)){
            setCheck(data,resourcesId);
        }
    }

    /**
     * 递归处理资源树选中状态
     * @param data
     * @param resourcesId
     */
    private void setCheck(List<TreeData> data,List<Object> resourcesId ){
        if(CollUtil.isNotEmpty(resourcesId)){
            data.stream().forEach(r->{
                if(CollUtil.contains(resourcesId,r.getId())){
                    r.setChecked(true);
                }
                setCheck(r.getChildren(),resourcesId);
            });
        }
    }

    /**
     * 根据用户code查询资源列表
     * @param partyCode
     * @return
     */
    @Override
    public List<Resource> listByPartyCode(String partyCode) {
        return baseMapper.listByPartyCode(partyCode);
    }


    /**
     * 根据用户code和机构code查询资源列表
     * @param partyCode 用户code
     * @param branchCode 机构code
     * @return
     */
    @Override
    public List<Resource> listByPartyCodeAndBranchCode(String partyCode,String branchCode ){
        return baseMapper.listByPartyCodeAndBranchCode(partyCode,branchCode);
    }

    /**
     * 获取权限的permission字符串list
     * @param resourceList
     * @return
     */
    @Override
    public List<String> getAllPermissionList(List<Resource> resourceList) {
        List<String> permissionList=new ArrayList<>();
        if(!CollectionUtils.isEmpty(resourceList)){
            resourceList.forEach(resource -> {
                permissionList.add(resource.getPermission());
            });
        }
        return permissionList;
    }

    @Override
    public List<ResourceVO> getList(String value) {
        return baseMapper.getList(value);
    }

    /**
     * 组装resource为树形结构
     * @param resourceList
     * @param levelStart 从哪级开始
     * @param maxLevel 最大总共获取多少级
     */
    private List<ResourceVO> treeResource(List<ResourceVO> resourceList,int levelStart,int maxLevel) {
        List<ResourceVO> topResourceList=new ArrayList<>();
        if(!CollectionUtils.isEmpty(resourceList)){
            topResourceList = resourceList.stream().filter(resourceVO -> resourceVO.getLevel()==levelStart).collect(Collectors.toList());
        }
        if(!CollectionUtils.isEmpty(topResourceList)){
            topResourceList.forEach(resource -> {
                resource.setChild(getChild(resource.getCode(),resourceList,maxLevel));
            });
        }
        return topResourceList;
    }

    /**
     * 获取子列表(递归)
     * @param parentCode 父级code
     * @param resourceList 总数据
     * @param maxLevel 最大总共获取多少级
     * @return
     */
    private List<ResourceVO> getChild(String parentCode, List<ResourceVO> resourceList,int maxLevel) {
        List<ResourceVO> child = resourceList.stream().filter(resource -> parentCode.equals(resource.getParentCode())).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(child)){
            child.forEach(resource -> {
                if(resource.getLevel()< maxLevel){//最大只展示maxLevel级
                    resource.setChild(getChild(resource.getCode(),resourceList,maxLevel));
                }
            });
        }
        return child;
    }
}
